<template>
  <!-- 添加或修改岗位对话框 -->
  <div class="conetr" v-loading="loading">
    <div class="center-board">
      <div class="center-title">
        <h3>代金券配置</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button icon="Download" type="success" plain @click="submitForm">保存配置</el-button>
      </div>
    </div>
    <el-form ref="formRef" :model="cmsArticle" :rules="rules" label-width="120px">
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="cmsArticle.type"
          placeholder="请选择类型"
          clearable
          @change="handleChange"
          style="width: 400px"
        >
          <el-option
            v-for="(item, index) in VOUCHER_TYPE_ENUM"
            :key="index"
            :label="item.label"
            :value="item.id"
            style="width: 400px"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品类" prop="supportedCategory" v-if="cmsArticle.type == 102">
        <el-select v-model="cmsArticle.supportedCategory" placeholder="请选择" style="width: 400px">
          <el-option label="无品类" :value="-1" v-if="cmsArticle.type != 102"></el-option>
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="券额" prop="amount">
        <el-input
          v-model="cmsArticle.amount"
          oninput="value=value.replace(/[^\d]/g,'')"
          style="width: 400px"
          maxlength="7"
          placeholder="请输入正整数"
        />
      </el-form-item>
      <!-- <el-form-item label="适用场景" prop="supportedMerchant" v-if="cmsArticle.type == 101">
        <div>
          <el-button type="primary" @click="shopVisible = true">设置门店</el-button>
          <el-dialog v-model="shopVisible" title="设置门店" width="600" :align-center="true">
            <div>
              <selectShop :tableData="cmsArticle.supportedMerchant"></selectShop>
            </div>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="shopVisible = false">关闭</el-button>
              </div>
            </template>
          </el-dialog>
          <div class="shop">
            <span v-for="item in cmsArticle.supportedMerchant" :key="item.companyId">
              {{ item.companyName }}
            </span>
          </div>
        </div>
      </el-form-item> -->

      <el-form-item label="有效日期" prop="effectiveType">
        <selectDate
          @change="handleEffec"
          style="width: 400px"
          :effectiveType="cmsArticle.effectiveType"
          :effectiveValue="cmsArticle.effectiveValue"
        ></selectDate>
      </el-form-item>
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker
          v-model="cmsArticle.publishTime"
          class="putime"
          type="datetime"
          format="YYYY/MM/DD HH"
          value-format="YYYY-MM-DD HH"
          style="width: 400px"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <el-form-item label="叠加规则" prop="overlayCount">
        <!-- <selectNumber
          style="width: 400px"
          :dataList="additivityList"
          :modelValue="cmsArticle.overlayCount"
          @update:modelValue="handleOverlay"
        ></selectNumber> -->
        <el-input
          v-model="cmsArticle.overlayCount"
          oninput="value=value.replace(/[^\d]/g,'')"
          style="width: 400px"
          maxlength="7"
          placeholder="请输入正整数"
        />
      </el-form-item>
      <el-form-item label="发行数量" prop="totalCount">
        <el-input
          v-model="cmsArticle.totalCount"
          oninput="value=value.replace(/[^\d]/g,'')"
          style="width: 400px"
          maxlength="7"
          placeholder="请输入正整数"
        />
      </el-form-item>
      <el-form-item label="领取数量" prop="exchangeCount">
        <el-input
          v-model="cmsArticle.exchangeCount"
          oninput="value=value.replace(/[^\d]/g,'')"
          style="width: 400px"
          maxlength="7"
          placeholder="请输入正整数"
        />
        <!-- <selectNumber
          :dataList="numberList"
          style="width: 400px"
          :modelValue="cmsArticle.exchangeCount"
          @update:modelValue="handleNumber"
        ></selectNumber> -->
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-switch
          v-model="cmsArticle.enable"
          inline-prompt
          active-text="正常"
          inactive-text="禁用"
          :active-value="1"
          :inactive-value="2"
        />
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import { ref, watch } from "vue";
const { proxy } = getCurrentInstance();
import listApi from "@/api/coupon/couponList";
import { VOUCHER_TYPE_ENUM } from "@/enums/coupon/coupon";
import selectNumber from "../selectNumber/index.vue";
import selectDate from "../selectDate/index.vue";
import selectShop from "../selectShop/index.vue";
import CommonAPI from "@/api/system/common";

// 1. 正确定义 props
const props = defineProps({
  // 1 是装修知识的type固定字段 2是装修案例
  type: {
    type: String,
    required: true,
    default: "",
  },
  couponData: {
    type: Object,
    default: null,
  },
});
const isEdit = ref(false); // 如果有默认值就是编辑
const loading = ref(false);
const categoryList = ref([]);
const shopVisible = ref(false);
const additivityList = ref([
  {
    label: 1,
    value: 1,
  },
  {
    label: 2,
    value: 2,
  },
  {
    label: 3,
    value: 3,
  },
]);
const numberList = ref([
  {
    label: 1,
    value: 1,
  },
  {
    label: 2,
    value: 2,
  },
  {
    label: "无上限",
    value: -1,
  },
]);
// 3. 监听父组件传入的 dialogShow
watch((newVal) => {
  // isEdit.value = !!props.couponData;
  if (props.couponData?.id) {
    isEdit.value = true;
  } else {
    isEdit.value = false;
  }
});

// 4. 定义 emit 以便向父组件通知状态变化
const emit = defineEmits(["backTo"]);

const handleEffec = (data) => {
  cmsArticle.value.effectiveType = data.effectiveType;
  cmsArticle.value.effectiveValue.day = data.day;
  cmsArticle.value.effectiveValue.begin = data.begin;
  cmsArticle.value.effectiveValue.end = data.end;
};
const handleOverlay = (data) => {
  cmsArticle.value.overlayCount = data;
};
const handleNumber = (data) => {
  cmsArticle.value.exchangeCount = data;
};

const cmsArticle = ref({
  amount: "",
  sort: 1,
  type: null,
  status: 1,
  coins: 0,
  // supportedMerchant: [], //可用门店
  effectiveType: 1, //有效期类型:1固定期限;2自定义时间区间
  effectiveValue: {
    day: 1,
    begin: "",
    end: "",
  },
  publishTime: "",
  overlayCount: 1,
  totalCount: 1,
  exchangeCount: 1,
  enable: 2,
  supportedCategory: -1,
});

const rules = ref({
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  amount: [{ required: true, message: "请输入券额", trigger: "blur" }],
  effectiveType: [{ required: true, message: "请选择有效时间", trigger: "change" }],
  // supportedMerchant: [{ required: true, message: "请选择门店", trigger: "change" }],
  publishTime: [{ required: true, message: "请选择发布时间", trigger: "change" }],
  overlayCount: [{ required: true, message: "请输入叠加规则", trigger: "blur" }],
  totalCount: [{ required: true, message: "请输入发行数量", trigger: "blur" }],
  exchangeCount: [{ required: true, message: "请输入发行数量", trigger: "blur" }],
  supportedCategory: [{ required: true, message: "请选择品类", trigger: "change" }],
});

function backTo() {
  resetData();
  emit("backTo");
}

function handleChange(val) {
  if (cmsArticle.value.type == 102) {
    cmsArticle.value.supportedCategory = "";
  } else {
    cmsArticle.value.supportedCategory = -1;
  }
}

const submitForm = async () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      let data = JSON.parse(JSON.stringify(cmsArticle.value));
      data.coins = data.amount * 10;
      data.publishTime = data.publishTime + ":00:00";
      if (isEdit.value == false) {
        methodAddArticle(data);
      } else {
        methodUpdateArticle(data);
      }
    }
  });
};

function disabledDate(time) {
  return time.getTime() < Date.now();
}

// 新增文章
async function methodAddArticle(params) {
  loading.value = true;
  try {
    await listApi.add(params);
    ElMessage.success("新增成功");
    backTo();
  } catch (err) {
  } finally {
    loading.value = false;
  }
}
// 修改
async function methodUpdateArticle(params) {
  try {
    await listApi.update(params);
    ElMessage.success("修改成功");
    backTo();
  } catch (err) {
  } finally {
    loading.value = false;
  }
}
// 查询
function handleQuery() {
  CommonAPI.getAllMaterialCategory({
    isLeaf: false,
    enable: true,
    level: 2,
  })
    .then((data) => {
      categoryList.value = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i].level === 2) {
          categoryList.value.push(data[i]);
        }
      }
    })
    .finally(() => {
      // loading.value = false;
    });
}

/**
 * 编辑文章的值处理
 */
const editDefaultData = () => {
  cmsArticle.value = props.couponData;
  // cmsArticle.value.enable = cmsArticle.value.enable == 1 ? true : false;
  let indexs = cmsArticle.value.publishTime.indexOf(":");
  cmsArticle.value.publishTime = cmsArticle.value.publishTime.slice(0, indexs);
  const isExist = additivityList.value.some((item) => item.value === cmsArticle.value.overlayCount);
  // 如果值不存在就在数组中添加一组
  if (isExist == false) {
    additivityList.value.push({
      label: cmsArticle.value.overlayCount,
      value: cmsArticle.value.overlayCount,
    });
  }
  const isnumber = numberList.value.some((item) => item.value === cmsArticle.value.exchangeCount);
  if (isnumber == false) {
    numberList.value.push({
      label: cmsArticle.value.exchangeCount,
      value: cmsArticle.value.exchangeCount,
    });
  }
};
const resetData = () => {
  cmsArticle.value = {
    amount: "",
    sort: 1,
    type: null,
    status: 1,
    // supportedMerchant: [], //可用门店
    effectiveType: 1, //有效期类型:1固定期限;2自定义时间区间
    effectiveValue: {
      day: 0,
      begin: "",
      end: "",
    },
    publishTime: "",
    overlayCount: "",
    totalCount: "",
    exchangeCount: "",
    enable: false,
    supportedCategory: -1,
  };
};

function empty() {
  ElMessageBox.confirm("确定要清空所有内容吗？", "提示", { type: "warning" }).then(() => {
    resetData();
  });
}
onMounted(() => {
  handleQuery();
  if (isEdit.value == true) {
    editDefaultData();
  } else {
    resetData();
  }
});
</script>
<style scoped lang="scss">
.putime {
}
:deep(.el-picker-panel__footer .el-picker-panel__link-btn .el-button--text) {
  display: none;
}
.conetr {
  padding: 10px;
  background-color: #fff;
  position: relative;
  flex: 1;
  margin-left: 10px;
  box-sizing: border-box;
  background-color: #fff;
  padding: 10px 20px;

  .center-board {
    .center-title {
      position: absolute;
      left: 20px;
    }
    .action-bar {
      position: relative;
      box-sizing: border-box;
      padding: 10px 0 15px 0;
      border-bottom: 1px solid var(--el-border-color-extra-light);
      display: flex;
      align-items: center;
      justify-content: flex-end;

      u .delete-btn {
        color: #f56c6c;
      }
    }
  }
  .shop {
    display: flex;
    width: 400px;
    border: 1px solid #eee;
    border-radius: 5px;
    flex-wrap: wrap;
    max-height: 400px;
    overflow-y: scroll;
    span {
      font-size: 12px;
      margin-bottom: 5px;
      margin-left: 5px;
    }
  }
}
</style>
